package controller;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.ModelAndView;

import util.DAOException;
import domain.Address;
import domain.Contact;
import domain.ContactGroup;
import domain.PhoneNumber;
import domain.factory.POJOFactory;
import domain.itf.IDAOContact;
import domain.itf.IDAOContactGroup;

/**
 * Controller implementation for add a new {@link Contact}.
 */
@Controller
@RequestMapping("/AddContact")
public class AddContactController {

	@Autowired
    ServletContext servletContext;
	
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView doGet(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("addContact");
		
		// get alls groups
		ApplicationContext context = WebApplicationContextUtils
				.getWebApplicationContext(servletContext);
		IDAOContactGroup daoContactGroup = (IDAOContactGroup) context.getBean("DAOContactGroup");
		List<ContactGroup> groups = daoContactGroup.getAllGroups();
		if (groups.isEmpty())
			view.addObject("groups", null);
		else
			view.addObject("groups", groups);
		return view;
	}

	@RequestMapping(method = RequestMethod.POST)
	public ModelAndView doPost(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("main");
		
		// general informations
		String firstName = request.getParameter("firstName");
		String lastName = request.getParameter("lastName");
		String emailC = request.getParameter("emailC");
		String numSiretString = request.getParameter("siret");
		
		// address
		String selectedAddress = request.getParameter("selectedAddress");
		
		String street = request.getParameter("street");
		String city = request.getParameter("city");
		String zip = request.getParameter("zip");
		String country = request.getParameter("country");
		
		// the phones
		String[] phones = request.getParameterValues("phoneNumbers");
		String[] kinds = request.getParameterValues("kindTypes");
		
		String[] groupsStrings = request.getParameterValues("groups");
		System.out.println("groupsStrings:" + groupsStrings);
		
		try {
			Integer numSiret = null;
			if (!numSiretString.isEmpty())
				numSiret = Integer.parseInt(numSiretString);
			
			ApplicationContext context = WebApplicationContextUtils
					.getWebApplicationContext(servletContext);
			
			// if the information are given, create the address
			Address address = null;
			if (street.length() > 0 || city.length() > 0 || zip.length() > 0 || country.length() > 0) {
				address = POJOFactory.instance.newAddress(street, city, zip, country);
				if(selectedAddress != null)
				{
					String[] tabSelectedAddress = selectedAddress.split("~");
					address.setId(Integer.parseInt(tabSelectedAddress[0]));
					address.setVersion(Long.parseLong(tabSelectedAddress[1]));
				}
			}
			
			// if the informations are given, create the phones numbers
			Set<PhoneNumber> phonesNumbers = new HashSet<PhoneNumber>();
			for (int i = 0; i < phones.length; i++) {
				if (!phones[i].isEmpty()) {
					phonesNumbers.add(POJOFactory.instance.newPhoneNumber(kinds[i], phones[i], null));
				}
			}
			if (phonesNumbers.isEmpty())
				phonesNumbers = null;

			IDAOContactGroup daoContactGroup = (IDAOContactGroup) context.getBean("DAOContactGroup");
			Set<ContactGroup> groups = new HashSet<ContactGroup>();
			if (groupsStrings != null && groupsStrings.length > 0) {
				for (String groupIdString : groupsStrings) {
					try {
						int groupId = Integer.parseInt(groupIdString);
						ContactGroup group = daoContactGroup.getById(groupId);
						
						if (group != null)
							groups.add(group);
					} catch (NumberFormatException e) {}
				}
			}
			if (groups.isEmpty())
				groups = null;
			
			// create the contact
			IDAOContact daoContact = (IDAOContact) context.getBean("DAOContact");
			Contact contact = daoContact.addContact(firstName, lastName, emailC, address, groups, phonesNumbers, numSiret);
			
			if (contact != null) {
				view.addObject("messageInfo", "You have succesful create the member.");
			} else {
				view.addObject("messageError", "An error occurs during the creation.");
			}
		} catch (DAOException e) {
			view.addObject("messageError", e.getMessage());
		}
		return view;
	}
}
